﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="QueryNoMap.aspx.cs" Inherits="Agents.Agent.QueryNoMap" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">

    <meta http-equiv="X-UA-Compatible" content="IE=7,IE=9" />

    <!--The viewport meta tag is used to improve the presentation and behavior of the samples

      on iOS devices-->

    <meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no"/>
    <link rel="stylesheet" type="text/css" href="http://serverapi.arcgisonline.com/jsapi/arcgis/2.4/js/dojo/dijit/themes/claro/claro.css">
    <link href="../Styles/SiteMaster.css" rel="stylesheet" type="text/css" />
    <script type="text/javascript" src="http://serverapi.arcgisonline.com/jsapi/arcgis/?v=2.4"></script>
    <script type="text/javascript" src="../Scripts/Common.js"></script>

    <style type="text/css" media="screen">

      .segment { cursor:pointer; padding-top:3px; padding-bottom:3px; }

    </style>

    <script type="text/javascript">
        dojo.require("esri.map");
        dojo.require("esri.tasks.locator");
        dojo.require("esri.tasks.route");
        dojo.require("esri.utils");

        var map, locator, routeTask, final, routeParams, routes = [];
        var fromSymbol, toSymbol, routeSymbol, segmentSymbol;
        var from, to, directions, directionFeatures, segmentGraphic;
        var times, routToClient, counter, helper;
        var max = 10000000;
        var maxAdress;
        function init() {
            esri.config.defaults.io.proxyUrl = "/proxy/proxy.ashx";

            final=0;
            map = new esri.Map("map");

            map.addLayer(new esri.layers.ArcGISTiledMapServiceLayer("http://www10.emap.co.il/ArcGIS/rest/services/eMap_vector_2010/MapServer"));

            locator = new esri.tasks.Locator("http://www10.emap.co.il/ArcGIS/rest/services/eMapComposite/GeocodeServer");
            dojo.connect(locator, "onError", errorHandler);

            routeTask = new esri.tasks.RouteTask("http://www10.emap.co.il/ArcGIS/rest/services/eMapRoute/NAServer/route");
            routeParams = new esri.tasks.RouteParameters();
            routeParams.stops = new esri.tasks.FeatureSet();
            routeParams.returnRoutes = true;
            routeParams.returnDirections = true;
            routeParams.outSpatialReference = new esri.SpatialReference({ wkid: 4326 });
            routeParams.directionsLengthUnits = esri.Units.KILOMETERS;
            dojo.connect(routeTask, "onSolveComplete", showRoute);
            dojo.connect(routeTask, "onError", errorHandler);
            
            //Configure symbols to be used for destinations and route segments
            fromSymbol = new esri.symbol.SimpleMarkerSymbol().setColor(new dojo.Color([0, 255, 0]));
            toSymbol = new esri.symbol.SimpleMarkerSymbol().setColor(new dojo.Color([255, 0, 0]));

            routeSymbol = new esri.symbol.SimpleLineSymbol().setColor(new dojo.Color([0, 0, 255, 0.5])).setWidth(4);
            segmentSymbol = new esri.symbol.SimpleLineSymbol().setColor(new dojo.Color([255, 0, 0, 0.5])).setWidth(8);
            getDirections();
        }

        dojo.addOnLoad(init);

        function getDirections() {
            counter= 0;
            helper=1;
            var from = '<%=addr %>';
            var to = new Array();
            times= new Array();
            routToClient= new Array();
            var sortedTimes= new Array();
            var date= new Array();
            var sortedDates= new Array();
            var name= new Array();
            var orders= new Array();
            var sortedOrders= new Array();
            var avgSum= new Array();
            var sortedSum= new Array();
            var prior= new Array();
            var sortedPriority= new Array();
            var grades= new Array();
            var sortedGrades= new Array();
            var str= new Array();
            var pr;
            var tot;
            var dis;
            var las;
            var av;
            var agent; 
            <%
            //This is pure server side area
            for(int i=0;i<size;i++)
             {
            %>
            to[<%=i%>] = '<%=Locations[i]%>'
            name[<%=i%>] = '<%=names[i]%>'
            date[<%=i%>] = '<%=dates[i]%>'
            orders[<%=i%>] = '<%=totalOrders[i]%>'
            avgSum[<%=i%>] = '<%=totalMoney[i]%>'
            str[<%=i%>] = '<%=priority[i]%>';
            <%
            } 
            %>

            var agent = '<%= agentName %>';
            var length = '<%= size %>';
            var av = '<%= avg %>';
            var las = '<%= last %>';
            var dis = '<%= dist %>';
            var pr = '<%= pri %>';
            var tot = '<%= total %>';

            var i;
            for(i=0;i<length;i++)
            {
                times[i]= 0;
                routToClient[i]="";
                grades[i]= 0.9;
                prior[i]= parseFloat(str[i]);
            }
            

            for (i = 0; i < length; i++) {
                sortedOrders[i]= orders[i];
            }
            sortedOrders.sort(function(a,b){return a - b}); 
            
            for (i = 0; i < length; i++) {
                sortedSum[i]= avgSum[i];
            }
            sortedSum.sort(function(a,b){return a - b}); 

            for (i = 0; i < length; i++) {
                sortedPriority[i]= prior[i];
            }
            sortedPriority.sort(function(a,b){return a - b}); 
            
            
            routeParams.stops.features = [];

            segmentGraphic = null;

            //Parse and geocode "from" address
            var fromArr = from.split(","), fromAddress = { City: fromArr[0], Street: fromArr[1], House: fromArr[2] };
            locator.addressToLocations(fromAddress, ["Loc_name"], 
                function(addressResults)   { 

                    // Add the agent's x and y location to the hidden fields
                    document.getElementById('hiddenLocationX').value = 
                                                addressResults[0].location.x;
                    document.getElementById('hiddenLocationY').value = 
                                                addressResults[0].location.y;

                    // Show the agent on the map
                    configureRoute(addressResults, "from", -1);

                    // Update the page to show notifications
                    if (document.getElementById('updatedAgentLocation').value == 'false') {
                        form1.submit();
                    }
                } );
            
            for (i = 0; i < length; i++) {
                //Parse and geocode "to" address
                var toArr = to[i].split(","), toAddress = { City: toArr[0], Street: toArr[1], House: toArr[2] };
                locator.addressToLocations(toAddress, ["Loc_name"], function (addressCandidates) { configureRoute(addressCandidates, "to", i); });
            }

            setTimeout(function(){
                
                for (i = 0; i < length; i++) {
                    sortedTimes[i]= times[i];
                }
                
                sortedTimes.sort(function(a,b){return a - b}); 
                
                for (i = 0; i < length; i++) {
                    grades[i]= (pr*prior[i])/10;
                  //  dojo.byId("summary").innerHTML = grades[i];
                }

                var j=0;
                var place;
                dojo.byId("summary").innerHTML = "in time zone1";
                //dojo.byId("summary").innerHTML = grades[0];
                //dojo.byId("summary").innerHTML = "client to go to: "+name[0]+"<br /> &nbsp;"+"time= "+times[0]+"<br /> &nbsp;"+routToClient[0];
                
                for (i = 0; i < length; i++) {
                    for (j = 0; j < length; j++) { 
                        if(orders[i]==sortedOrders[j]){
                            grades[i]+= (j/length)*tot;
                            j= length;
                        }
                    }
                }
                
                for (i = 0; i < length; i++) {
                    for (j = 0; j < length; j++) { 
                        if(avgSum[i]==sortedSum[j]){
                            grades[i]+= (j/length)*av;
                            j= length;
                        }
                    }
                }
                dojo.byId("summary").innerHTML = "in time zone2";
                for (i = 0; i < length; i++) {
                    for (j = 0; j < length; j++) { 
                        if(times[i]==sortedTimes[j]){
                            grades[i]+= ((length-j)/length)*dis;
                            j= length;
                        }
                    }
                }
                
                for (i = 0; i < length; i++) {
                    sortedGrades[i]= grades[i];
                }
                
                sortedGrades.sort(function(a,b){return a - b}); 
           
                for (j = 0; j < length; j++) { 
                    if(grades[j]==sortedGrades[length-1]){

                        dojo.byId("empty").innerHTML = "כתובת: " + to[j];
                        dojo.byId("summary").innerHTML = "לקוח: "+name[j]+"<br />"+"זמן נסיעה: "+
                        formatTime(times[j]) +"<br /> &nbsp;"+routToClient[j];
                        PageMethods.GoingTo(name[j], agent);
                        j= length;
                    }
                }

            }, 9000);
        }

        function configureRoute(addressCandidates, type, num) {
            var stop = null, score = 0;
            //Get the address match with the top score
            dojo.forEach(addressCandidates, function (candidate) {
                if (candidate.score > score) {
                    stop = candidate;
                    score = candidate.score;
                }
            });

            var location = stop.location;
            
            //Set the best address match as a stop on the route
            if (type == "from") {
                routeParams.stops.features[0] = map.graphics.add(new esri.Graphic(location, fromSymbol, { address: stop.address, score: stop.score }));
            }
            else {
                routeParams.stops.features[1] = map.graphics.add(new esri.Graphic(location, toSymbol, { address: stop.address, score: stop.score }));
            }
            //If both the "to" and the "from" addresses are set, solve the route
            if (routeParams.stops.features.length === 2){

                routeTask.solve(routeParams);
            }
        }

        function showRoute(solveResult) {
            num= counter;
            counter++;
            directions = solveResult.routeResults[0].directions;
            directionFeatures = directions.features;
            if(final== 1){
                //Add route to the map
                map.graphics.add(new esri.Graphic(directions.mergedGeometry, routeSymbol));

                //Display the total time and distance of the route
                dojo.byId("summary").innerHTML = "<br /> &nbsp; מרחק כולל: " + formatDistance(directions.totalLength, "מטרים") +
                     "<br /> &nbsp; זמן כולל: " + formatTime(directions.totalTime);
            }
            
            //if(final== 0)
            if (max > directions.totalTime) {
                max = directions.totalTime;
                var id = directions.routeName.split("-")[1].split(",");
                maxAdress = id[2] + "," + id[0] + "," + id[1];
                //dojo.byId("empty").innerHTML = "כתובת: " + maxAdress;
                //map.graphics.add(new esri.Graphic(directions.mergedGeometry, routeSymbol));
            }
            // List the directions and create hyperlinks for each route segment
            var dirStrings = ["<ol>"];
            dojo.forEach(solveResult.routeResults[0].directions.features, function (feature, i) {

                var currTime = formatTime(feature.attributes.time);
                var currDist = formatDistance(feature.attributes.length, "ק\"מ");
                var currDirString = currDist;

                if (currTime != "") {
                    currDirString += ", " + currTime;
                }

                dirStrings.push("<li onclick='zoomToSegment(" + i + "); return false;' class=\"segment\"><a href=\"#\">" + 
                feature.attributes.text + " (" + currDirString + ")</a></li>");
            });
            dirStrings.push("</ol>");
            
            //dojo.byId("summary").innerHTML =  dirStrings.join("");
            times[num]= directions.totalTime;
            routToClient[num]= dirStrings.join("");

            // Enable the "continue to client" button
            document.getElementById("btnContinue").disabled = false;
        }
         
        //Display any errors that were caught when attempting to solve the rotue
        function errorHandler(err) {
            alert("התרחשה שגיאה\n" + err.message + "\n" + err.details.join("\n"));
        }

        //Zoom to the appropriate segment when the user clicks a hyperlink in the directions list
        function zoomToSegment(index) {
            var segment = directionFeatures[index];
            map.setExtent(segment.geometry.getExtent(), true);
            if (!segmentGraphic) {
                segmentGraphic = map.graphics.add(new esri.Graphic(segment.geometry, segmentSymbol));
            }
            else {
                segmentGraphic.setGeometry(segment.geometry);
            }
        }

        function zoomToFullRoute() {
            map.graphics.remove(segmentGraphic);
            segmentGraphic = null;
            map.setExtent(directions.extent, true);
        }

        //Format the time as hours and minutes
        function formatTime(time) {
            var hr = Math.floor(time / 60), //Important to use math.floor with hours
            min = Math.round(time % 60);

            if (hr < 1 && min < 1) {
                return "";
            }
            else if (hr < 1) {
                return min + " דקות";
            }

            return hr + " שעות " + min + " דקות";
        }

        //Round the distance to the nearest hundredth of a unit
        function formatDistance(dist, units) {

            var d = Math.round(dist * 100) / 100;

            if (d < 1) {
                return ((dist * 100) % 100).toFixed(2) + " מטרים";
            }

            return d + " " + units;
        }

    </script>

  </head>
  <body dir="rtl">
      <form id="form1" runat="server" autocomplete="off">
        <asp:HiddenField runat="server" id="hiddenLocationX" />
        <asp:HiddenField runat="server" id="hiddenLocationY" />
        <asp:HiddenField runat="server" id="updatedAgentLocation" value="false" />
        <div>
        <table border="0" width="100%">
        <tr class="header">
            <td colspan="2">
                <asp:Image ID="Image1" runat="server" ImageUrl="~/images/background.jpg" ImageAlign="Middle" />
            </td>
        </tr>
        <tr class="mainContent">
            <td width="100%" bgcolor="white">
                <asp:ScriptManager ID="ScriptManager1" 
                EnablePageMethods="true" 
                EnablePartialRendering="true" runat="server" />
    
                <input id="inpHide" type="hidden" runat="server" />
                <br /><br />

                <table>
                  <tbody>
                    <tr>
                      <td>
                        <div id="map" style="width:600px; height:400px; border:1px solid #000;"></div>
                      </td>
                      <td valign="top">
                        <div style="width:400px; height:400px; overflow:auto; border:1px solid #000;">
                         <asp:Label ID="empty" runat="server" />
                          <div id="summary" onclick="zoomToFullRoute();" class="segment">המתן...</div>
                          <div id="directions"></div>
                        </div>
                      </td>
                    </tr>
                  </tbody>
                </table>
            </td>
        </tr>
        <tr>
            <td colspan="2" class="footer"/>
        </tr>
        </table>
    
        </div>

        <div class="alignCenter">
                <asp:Button ID="btnContinue" Text="המשך ללקוח" runat= "server" 
                    onclick="btn_Click1" CssClass="button" Enabled="false"/>            
        </div>
        </form>
    </body>
</html>
